import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

export interface Version {
  id: number;
  project_id: number;
  version_number: string;
  status: string;
  download_status: string;
  upload_status: string;
  error_message: string | null;
  created_at: string;
  completed_at: string | null;
}

interface VersionsState {
  items: Version[];
  status: 'idle' | 'loading' | 'succeeded' | 'failed';
  error: string | null;
}

const initialState: VersionsState = {
  items: [],
  status: 'idle',
  error: null,
};

export const fetchVersions = createAsyncThunk(
  'versions/fetchVersions',
  async (projectId: number) => {
    const response = await axios.get(`/api/projects/${projectId}/versions`);
    return response.data;
  }
);

export const createVersion = createAsyncThunk(
  'versions/createVersion',
  async (versionData: Partial<Version>) => {
    const response = await axios.post('/api/versions', versionData);
    return response.data;
  }
);

export const fetchVersionStatus = createAsyncThunk(
  'versions/fetchVersionStatus',
  async (versionId: number) => {
    const response = await axios.get(`/api/versions/${versionId}/status`);
    return response.data;
  }
);

const versionsSlice = createSlice({
  name: 'versions',
  initialState,
  reducers: {
    updateVersionStatus(state, action) {
      const { id, ...updates } = action.payload;
      const version = state.items.find(v => v.id === id);
      if (version) {
        Object.assign(version, updates);
      }
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchVersions.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchVersions.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.items = action.payload;
      })
      .addCase(fetchVersions.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message || null;
      })
      .addCase(createVersion.fulfilled, (state, action) => {
        state.items.push(action.payload.version);
      })
      .addCase(fetchVersionStatus.fulfilled, (state, action) => {
        const index = state.items.findIndex(v => v.id === action.payload.id);
        if (index !== -1) {
          state.items[index] = action.payload;
        }
      });
  },
});

export const { updateVersionStatus } = versionsSlice.actions;
export default versionsSlice.reducer;
